package com.co.server.service.user.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.co.common.dao.BaseDao;
import com.co.common.service.BaseServiceImpl;
import com.co.common.utils.MD5;
import com.co.common.utils.ValidateUtil;
import com.co.server.constant.Constant;
import com.co.server.dao.user.TUsersDao;
import com.co.server.entity.user.TUserActive;
import com.co.server.entity.user.TUsers;
import com.co.server.entity.user.aide.TUsersConstant;
import com.co.server.entity.user.aide.TUsersQuery;
import com.co.server.service.user.TUserActiveService;
import com.co.server.service.user.TUsersService;

@Service
public class TUsersServiceImpl extends BaseServiceImpl<TUsers, Integer> implements TUsersService {
    @Resource
    private TUsersDao tUsersDao;
    
    @Resource
    private TUserActiveService tUserActiveService;

    @Override
    protected BaseDao<TUsers, Integer> getBaseDao() {
        return tUsersDao;
    }

	public TUsers queryByLoginName(String username) {
		TUsersQuery query = new TUsersQuery();
		query.setUserName(username);
		return queryOne(query);
	}

	public void updateLogin(UsersSession oldUsersSession, TUsers tUsers,String ipAddress) {
		//修改用户登录信息
		Short visitCountInit = 1;
		tUsers.setLastTime(new Date());
		tUsers.setLastIp(ipAddress);
		Short visitCount = tUsers.getVisitCount();
		if(visitCount == null){
			tUsers.setVisitCount(visitCountInit);
		}else{
			visitCount++;
			tUsers.setVisitCount(visitCount);
		}
		updateById(tUsers);
		oldUsersSession.settUsers(tUsers);
		oldUsersSession.setLogin(true);
	}

	public void addUser(TUsers tUsers,TUserActive tUserActive) {
		tUsers.setCreateTime(new Date());
		tUsers.setStatus(Constant.STATUS_ACTIVE);
		//用户注册送10个积分
		tUsers.setGrade(TUsersConstant.USER_GRADE_FOR_REGISTER);
		String userName = tUsers.getUserName();
		if(ValidateUtil.isMobile(userName)){
			tUsers.setMobilePhone(userName);
		}
		if(ValidateUtil.isEmail(userName)){
			tUsers.setEmail(userName);
		}
		tUsers.setDisplayName(userName);
		
		//密码加密
		tUsers.setUserPassword(MD5.encodeStr(tUsers.getUserPassword()));
		
		add(tUsers);
		TUserActive tUserActiveTmp = new TUserActive();
		tUserActiveTmp.setId(tUserActive.getId());
		tUserActiveTmp.setIsUse(Constant.YES);
		tUserActiveTmp.setUsetime(new Date());	
		tUserActiveService.updateByIdSelective(tUserActiveTmp);
	}

	public void updateUserGrade(TUsers user, Integer Change) {
		if(Change !=null){
			Integer grade = user.getGrade();
			if(grade == null){
				grade=Change;
			}else{
				grade=grade+Change;
			}
			TUsers tUsers = new TUsers();
			tUsers.setUserId(user.getUserId());
			tUsers.setGrade(grade);
			updateByIdSelective(tUsers);
		}
	}

	public void updateUserGrade(Integer userId, Integer Change) {
		TUsers user = queryById(userId);
		updateUserGrade(user,Change);
	}
}